<template>
  <div class="common-layout">
    <el-form class="header" :model="queryParam" ref="queryRef" :inline="true">

      <el-form-item label="测试">
        <el-select @change="timesChange" style="width: 200px" clearable v-model="queryParam.times"
                   placeholder="请选择测试范围">
          <el-option
              v-for="dict in word_test_scope"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary"
                   style="width:100px;"
                   @click="searchByUnit">重新加载
        </el-button>

        <el-button
            v-if="false"
            type="success"
            @click="submitRecordTest"
            style="width:100px;margin-left: 20px"
        >
          提交
        </el-button>

        <el-button
            type="danger"
            @click="loadWordAllTest"
            style="width:100px;margin-left: 20px"
        >
          整体测试
        </el-button>

        <div class="time-display">
          {{ formattedTime }}
        </div>

        <el-button
            plain
            type="primary"
            :disabled="isRunning || (isCountdown && initialTime === 0 && currentTime === 0)"
            @click="startTimer"
        >
          {{
            isCountdown && currentTime === 0 && initialTime > 0 && !isRunning ? '开始倒计时' : (isRunning ? '运行中' : '启动')
          }}
        </el-button>

        <el-button
            plain
            type="warning"
            :disabled="!isRunning"
            @click="pauseTimer"
        >
          暂停
        </el-button>

        <el-button
            plain
            :disabled="isRunning"
            @click="resetTimer"
        >
          重置
        </el-button>

      </el-form-item>
    </el-form>

    <el-row :gutter="20" style="margin: 0 20px">
      <el-col :span="6" v-for="(item, index) in questionsData" :key="index" style="margin-bottom: 20px">
        <el-card shadow="hover" @mouseenter="">
          <div style="padding: 8px;">
            <strong> {{ index + 1 }}.</strong>
            <span class="word_show"  style="font-size: 20px;color: #409EFF;font-weight: bold">{{ item.name }}</span><span>(</span>
            <span style="color: purple;font-size: 12px">{{ item.type }}</span><span>)</span>
            <span @click="buttonClick(item)" style="color: blue;float: right;cursor: pointer">发音</span>
            <div style="margin-top: 10px;display: flex;flex-direction: column;gap: 8px" class="bottom card-header">
              <button
                  v-for="(opt, idx) in item.options"
                  :key="idx"
                  class="option"
                  :class="{
                    hiddenAll: item.enabled,
                    selected: userAnswers[item.id] === opt,
                    correct: showResult && opt === item.chinese,
                    wrong: showResult && userAnswers[item.id] === opt && opt !== item.chinese
                  }"
                  @click="selectOption(item.id, opt)"
                  :disabled="showResult"
              >
                {{ String.fromCharCode(65 + idx) }}. {{ opt }}
              </button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <div class="actions">
      <button v-if="!showResult" @click="submit" class="btn-submit">
        提交答案
      </button>
    </div>

    <!-- 结果显示 -->
    <div v-if="showResult" class="result">
      <h4>
        答对 {{ questionsData.filter(q => userAnswers[q.id] === q.chinese).length }} / {{ total }} 题
      </h4>
      <p :style="{ color: accuracy >= 80 ? '#52c41a' : accuracy >= 60 ? '#faad14' : '#f5222d' }">
        正确率：{{ correctRate }}%
      </p>
    </div>
  </div>
</template>

<script setup>
import {getPageUnitTimes, handleColumnAudio, insertDataToNewRecord} from "@/api/word/index.js";
import {getCurrentInstance, ref} from 'vue'
import {parseTime} from "@/utils/ruoyi.js";
import {addWordTest, getUsedTime} from "@/api/word/wordRecord.js";
import router from "@/router/index.js";
import {isPartialEqual, shuffleArray, shuffleArrayLength} from "@/api/utils/index.js";
import {useTimerStore} from "@/store/timer.js";
import '@/assets/styles/word-common.css'

let time_value = ref(Date.now())

const {proxy} = getCurrentInstance();
const {word_test_scope} = proxy.useDict("word_test_scope")
const route = useRoute()
//初始化题目+选项-new
const showResult = ref(false)
const hiddenAllStatus = ref(true)
const questionsData = ref([])
const testWord = ref({})
const chineseWords = computed(() => Object.values(testWord.value))  // 所有中文意思（用于生成干扰项）
const userAnswers = ref({}) // 用户选择
const userTime = ref({})   // 用户点击时间
const correctNum = ref(0)
const correctRate = ref('')
const recordSubmit = ref({})
const testWordNum = ref({})
const testWordType = ref({})
let recordFrom = ref({})

//时间
const timerStore = useTimerStore();
// 从 store 中解构 actions
timerStore.isCountdown = true;
timerStore.initialTime = 360
const {startTimer, pauseTimer, resetTimer, setInitialTime} = timerStore;
// 从 store 中解构 state 和 getters (保持响应性)
const {formattedTime, isRunning, isCountdown, initialTime, currentTime} = storeToRefs(timerStore); // 添加 currentTime

// 设定倒计时
const handleSetInitialTime = (value) => {
  const newTime = Number(value);
  // console.log(newTime)
  if (!isNaN(newTime) && newTime >= 0) {
    setInitialTime(newTime);
  } else {
    setInitialTime(timerStore.initialTime);
  }
};

let pageData = ref([])
let anotherData = ref([])
let anotherDataType = ref([])
let anotherDataTypeChinese = ref([])

let total = ref(0)
let testTimes = ref(1)
let testStartTime = ref(null)
let testEndTime = ref(null)
let testStartTimeStatus = ref(true)
let wordClicked = ref(0)
let practiceId = ref(null)
let queryParam = ref({
  unit: '',
  book: '',
  times: '1',
  pageSize: 10
})

let queryParamAnother = ref({
  unit: '',
  book: '',
  times: '1'
})

initPage()

async function initPage() {
  queryParam.value.unit = route.query.unit
  queryParam.value.book = route.query.book
  queryParam.value.times = '1'
  await loadAnotherWord()
  handleSetInitialTime()
  await handleQueryTimes()
  practiceId.value = Math.random().toString().substring(2)
  addFilterBlur()
}

async function loadAnotherWord() {
  queryParamAnother.value.unit = null
  queryParamAnother.value.book = 'book' + Math.ceil(Math.random() * 6)
  await getPageUnitTimes(queryParamAnother.value).then((res) => {
    if (res.code === 200 && res.data !== undefined) {
      anotherData.value = res.data
      anotherData.value.forEach((item) => {
        delete item._id
        delete item.book
        delete item.unit
        delete item.number
      })
    }
  })
}

//发音以及附加功能
function buttonClick(item) {
  deleteFilterBlur(item)
  handleColumnAudio(item)
}

function loadWordAllTest() {
  const route = router.resolve({
    path: '/word-all-test',
    query: queryParam.value
  })
  window.open(route.href, '_blank')
}

//连接MYSQL数据库-插入数据
function handleInsertRecordData(data) {
  // console.log(data)
  data.type = 'middle'
  addWordTest(data).then(res => {
    // console.log(res)
    recordFrom.value = {}
    if (res.code === 200) {
      // testResultWindowData(wordClicked.value)
      practiceId.value = Math.random().toString().substring(2)
      // proxy.$modal.msgSuccess("提交成功")
      wordClicked.value = 0
      testStartTimeStatus.value = true
    }
  })
}

function timesChange(times) {
  // console.log(times)
  if (times == null || times === '' || times === undefined) {
    testTimes.value = 1
    return
  }
  testTimes.value = times
}

async function searchByUnit() {
  if (queryParam.value.unit === undefined) {
    proxy.$modal.msgWarning("请选择单元")
    return
  }
  if (queryParam.value.book === undefined) {
    proxy.$modal.msgWarning("请选择书名")
    return
  }
  if (queryParam.value.times === undefined) {
    proxy.$modal.msgWarning("请选择测试范围")
    return
  }
  correctNum.value = 0
  proxy.$modal.msg("查询的书名:" + queryParam.value.book + "  课程名称:" + queryParam.value.unit)
  await handleQueryTimes()
  // console.log(total.value)
  time_value.value = Date.now() + 1000 * total.value * 6
  resetTimer()
  addFilterBlur()

  // console.log(total.value)
}

async function handleQueryTimes() {
  // console.log(queryParam.value)
  testWordNum.value = {}
  testWordType.value = {}
  testWord.value = []
  await getPageUnitTimes(queryParam.value).then((res) => {
    if (res.code === 200 && res.data !== undefined) {
      pageData.value = shuffleArray(res.data)
      total.value = res.data.length
    }
  })

  pageData.value.forEach(item => {
    testWord.value[item.name] = item.chinese
    testWordNum.value[item.name] = item.number
    testWordType.value[item.name] = item.type
  })
  initQuestions()
}

//隐藏选项功能
function addFilterBlur() {
  let value = questionsData.value;
  // console.log(value)
  value.forEach((item) => {
    item.enabled = true
  })
}

function deleteFilterBlur(pointer) {
  // console.log(pointer)
  if (pointer.enabled){
    pointer.enabled = false
  }
}

function getSimilarData(type) {
  type = type === null ? '' : type
  if (type !== '' && type.indexOf('+') > 0) {
    let number = Math.random() < 0.5 ? 0 : 1;
    type = type.split('+')[number]
  }
  if (type !== '') {
    if (type.toString().toLowerCase() === 'n' ||
        type.toString().toLowerCase() === 'v' ||
        type.toString().toLowerCase() === 'adj') {
      anotherDataType.value = anotherData.value.filter(item => {
        return item.type !== null && item.type.toLowerCase() === type.toLowerCase()
      })
      anotherDataType.value = shuffleArrayLength(anotherDataType.value,60)
    }
  } else {
    anotherDataType.value = anotherData.value.filter(item => {
      return item.type === null
    })
  }
  anotherDataTypeChinese.value = []
  anotherDataType.value.forEach(item => {
    anotherDataTypeChinese.value.push(item.chinese)
  })
}

const initQuestions = () => {
  const wordList = Object.keys(testWord.value)
  const list = []
  // console.log(anotherData.value)
  for (let i = 0; i < total.value; i++) {
    const name = wordList[i]
    const chinese = testWord.value[name]
    const type = testWordType.value[name]
    getSimilarData(type)
    const number = parseInt(testWordNum.value[name])
    const distractors = generateDistractors(chinese, anotherDataTypeChinese.value)
    const options = shuffle([chinese, ...distractors])

    list.push({
      id: `q${i + 1}`,
      name,
      type,
      number,
      options,
      chinese
    })
  }
  questionsData.value = list
  // console.log(pageData.value)

  userAnswers.value = {}
  userTime.value = {}
  showResult.value = false
}

// 选择选项
const selectOption = (qid, option) => {
  userAnswers.value[qid] = option
  userTime.value[qid] = parseTime(new Date())

  //记录首次点击的时间
  if (testStartTimeStatus.value) {
    testStartTime.value = Date.now()
    time_value.value = Date.now() + 1000 * total.value * 6
    testStartTimeStatus.value = false
  }
  startTimer()
}

// 打乱数组
const shuffle = (arr) => {
  const a = [...arr]
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[a[i], a[j]] = [a[j], a[i]]
  }
  return a
}

// 生成干扰项（3个错误选项）
const generateDistractors = (correct, all) => {
  return shuffle(all.filter(w => w !== correct)).slice(0, 3)
}

// 提交测试
const submit = () => {
  // console.log(userAnswers.value)
  if (Object.keys(userAnswers.value).length === 0) {
    proxy.$modal.msgError("未记录任何测试记录,请确认")
    return
  }
  let checkData = '还有未完成的测试'
  if (Object.keys(userAnswers.value).length === total.value) {
    checkData = '您已完成所有的测试'
  }
  let confirmString = checkData + ",是否确认提交?"
  proxy.$modal.confirm(confirmString).then(function () {
    testEndTime.value = Date.now()
    // pauseTimer()
    submitData()
    proxy.$modal.msgSuccess("提交成功")
  }).catch(() => {
    proxy.$modal.msg("取消提交")
  })
}

function submitData() {
  correctNum.value = 0
  questionsData.value.forEach(q => {
    q['selected'] = userAnswers.value[q.id]
    q['practiceId'] = practiceId.value
    q['time'] = userTime.value[q.id]
    if (userAnswers.value[q.id] === q.chinese) correctNum.value++
  })
  const accuracy = (correctNum.value / total.value) * 100
  correctRate.value = accuracy.toFixed(1)

  recordSubmit.value['data'] = questionsData.value
  recordSubmit.value['book'] = queryParam.value.book
  recordSubmit.value['unit'] = queryParam.value.unit

  // console.log(recordSubmit.value)
  insertDataToNewRecord(recordSubmit.value)

  //构建mysql数据
  recordFrom.value.book = queryParam.value.book
  recordFrom.value.unit = queryParam.value.unit
  recordFrom.value.times = queryParam.value.times
  recordFrom.value.practice = practiceId.value
  recordFrom.value.wordNum = total.value
  recordFrom.value.complete = Object.keys(userAnswers.value).length
  recordFrom.value.correctNum = correctNum.value
  recordFrom.value.way = 3
  recordFrom.value.usedTime = getUsedTime((testEndTime.value - testStartTime.value) / 1000)
  recordFrom.value.correctRate = parseFloat(correctNum.value / total.value).toFixed(2)

  // console.log(recordFrom.value)
  handleInsertRecordData(recordFrom.value)

  showResult.value = true
}
</script>

<style scoped lang="scss">

:deep(.el-radio__label) {
  font-size: 32px;
  line-height: 2;
}

.header {
  margin-top: 20px;
  margin-left: 20px;
}

.option:hover:not(.selected):not(:disabled) {
  background: #91d5ff;
  color: white;
}

.options {
  flex-wrap: wrap;
  gap: 8px; /* 项目间距 */
}

.option {
  flex: 1;
  padding: 8px 12px;
  background: #f0f8ff;
  border: 1px solid #91d5ff;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.option.selected {
  background: #1890ff;
  color: white;
  border-color: #1890ff;
}

.option.correct {
  background: #52c41a;
  color: white;
  border-color: #52c41a;
}

.option.wrong {
  background: #f5222d;
  color: white;
  border-color: #f5222d;
}

.option:disabled {
  cursor: not-allowed;
  opacity: 0.8;
}

:deep(.el-radio__label) {
  font-size: 32px;
  line-height: 2;
}

.actions {
  text-align: center;
  margin: 20px 0;
}

.btn-submit {
  padding: 10px 24px;
  background: #67C23A;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
}

.btn-submit:hover {
  background: #40a9ff;
}

.result {
  text-align: center;
  margin-top: 20px;
  font-weight: bold;
  font-size: 1.2em;
}

.option.hiddenAll{
  filter: blur(8px);
}
</style>
